package keter.sec.springsec.config;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.AnsiSqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import javax.sql.DataSource;

@Configuration
@Profile({"sqlite"})
public class DataSourceConfig {
	DruidPlugin plugin;

	@Value("${db.url}")
	private String dbUrl;
	@Value("${db.username}")
	private String username;
	@Value("${db.password}")
	private String password;

	/**
	 * 如果不返回DataSource对象
	 * spring在执行scheme.sql和data.sql的内容时
	 * 会自动调用hsql驱动向默认的hsql数据源（内存）初始化数据库。
	 * @return 
	 * @author gulixing@msn.com
	 * @date   2017年1月8日
	 */
	@Bean
	public  DataSource initDB(){
		return getDataSource(dbUrl, username, password);
	}

	private DataSource getDataSource(String dbUrl, String username, String password) {
		if(plugin!=null){
			return plugin.getDataSource();
		}
		plugin = new DruidPlugin(dbUrl, username, password);
		ActiveRecordPlugin arp = new ActiveRecordPlugin(plugin);
		arp.setDialect(new AnsiSqlDialect());
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
		plugin.start();
		arp.start();
		return plugin.getDataSource();
	}
}